﻿using System.Windows;
using Bookvar.UI.Arrangers;

namespace Bookvar.UI.Arrangers
{
    public class NormalTopicArranger : TopicArranger
    {
        #region TotalHeight

        private static readonly DependencyProperty TotalHeightProperty =
            DependencyProperty.Register( "TotalHeightProperty", typeof( double ), typeof( NormalTopicArranger ) );

        public static void SetTotalHeight( DependencyObject element, double value )
        {
            element.SetValue( TotalHeightProperty, value );
        }

        public static double GetTotalHeight( DependencyObject element )
        {
            return (double) element.GetValue( TotalHeightProperty );
        }

        #endregion

        public NormalTopicArranger( MindMapPanel panel ) : base( panel )
        {
        }

        protected internal override void ArrangeMainTopic( TopicContentPresenter mainTopicPresenter, Size size )
        {
            SetLeft( mainTopicPresenter, ( size.Width - mainTopicPresenter.ActualWidth ) / 2 );
            SetTop( mainTopicPresenter, ( size.Height - mainTopicPresenter.ActualHeight ) / 2 );

            CalculateTotalHeight( mainTopicPresenter );
        }

        private static double CalculateTotalHeight( TopicContentPresenter presenter )
        {
            double totalHeight = 0;
            totalHeight += presenter.DesiredSize.Height;
            foreach ( TopicContentPresenter child in presenter.Children )
            {
                totalHeight += CalculateTotalHeight( child );
            }

            SetTotalHeight( presenter, totalHeight );
            return totalHeight;
        }

        protected override void ArrangeChildTopics( TopicContentPresenter parentPresenter)
        {
            double parentLeft = GetLeft( parentPresenter );
            double parentTop = GetTop( parentPresenter );
            for ( int i = 0; i < parentPresenter.Children.Count; i++ )
            {
                TopicContentPresenter child = parentPresenter.Children[ i ];
                SetLeft( child, parentLeft + ( child.Topic.Depth * 10 ) );
                SetTop( child, parentTop + parentPresenter.DesiredSize.Height );
                parentTop += GetTotalHeight( child );
            }

            base.ArrangeChildTopics( parentPresenter);
        }
    }
}